package com.example.watchcat2k.finalproject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.DrawableContainer;
import android.media.Image;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;

public class MainActivity extends AppCompatActivity {
    //用户信息
    private User_basic_info my_info;

    private TextView textView_main_app_name;
    private ImageView imageView_main_home;
    private ImageView imageView_main_add;
    private ImageView imageView_main_person;
    private ImageView imageView_main_search;
    private ImageView imageView_main_menuBar;
    private FragmentManager fragmentManager;
    private HomeFragment homeFragment = new HomeFragment();
    private PersonFragment personFragment = new PersonFragment();
    View popupWindow_view;
    private PopupWindow popupWindow;
    private ConstraintLayout constraintLayout_main_container;

    //popupwindow的控件ID
    private de.hdodenhof.circleimageview.CircleImageView circleImageView_menu_image;
    private TextView textView_menu_username;
    private TextView textView_menu_summary;
    private ConstraintLayout constraintLayout_menu_fan;
    private ConstraintLayout constraintLayout_menu_blog;
    private ConstraintLayout constraintLayout_menu_picture;
    private ConstraintLayout constraintLayout_menu_video;
    private ConstraintLayout constraintLayout_menu_like;
    private ConstraintLayout constraintLayout_menu_follow;
    private ConstraintLayout constraintLayout_menu_question;
    private ConstraintLayout constraintLayout_menu_add;
    private ConstraintLayout constraintLayout_menu_feedback;
    private ConstraintLayout constraintLayout_menu_setting;
    private ConstraintLayout constraintLayout_menu_exit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView_main_app_name = (TextView) findViewById(R.id.textView_main_app_name);
        imageView_main_home = (ImageView) findViewById(R.id.imageView_main_home);
        imageView_main_add = (ImageView) findViewById(R.id.imageView_main_add);
        imageView_main_person = (ImageView) findViewById(R.id.imageView_main_person);
        imageView_main_search = (ImageView) findViewById(R.id.imageView_main_search);
        imageView_main_menuBar = (ImageView) findViewById(R.id.imageView_main_menuBar);
        fragmentManager = getSupportFragmentManager();
        popupWindow = null;
        popupWindow_view = getLayoutInflater().inflate(R.layout.popupwindow_menu_bar, null, false);


        constraintLayout_main_container = (ConstraintLayout) findViewById(R.id.constraintLayout_main_container);

        //popupwindow的控件ID
        circleImageView_menu_image = (CircleImageView) popupWindow_view.findViewById(R.id.circleImageView_menu_image);
        textView_menu_username = (TextView) popupWindow_view.findViewById(R.id.textView_menu_username);
        textView_menu_summary = (TextView) popupWindow_view.findViewById(R.id.textView_menu_summary);
        constraintLayout_menu_fan = (ConstraintLayout) popupWindow_view.findViewById(R.id.constraintLayout_menu_fan);
        constraintLayout_menu_blog = (ConstraintLayout) popupWindow_view.findViewById(R.id.constraintLayout_menu_blog);
        constraintLayout_menu_picture = (ConstraintLayout) popupWindow_view.findViewById(R.id.constraintLayout_menu_picture);
        constraintLayout_menu_video = (ConstraintLayout) popupWindow_view.findViewById(R.id.constraintLayout_menu_video);
        constraintLayout_menu_like = (ConstraintLayout) popupWindow_view.findViewById(R.id.constraintLayout_menu_like);
        constraintLayout_menu_follow = (ConstraintLayout) popupWindow_view.findViewById(R.id.constraintLayout_menu_follow);
        constraintLayout_menu_question = (ConstraintLayout) popupWindow_view.findViewById(R.id.constraintLayout_menu_question);
        constraintLayout_menu_add = (ConstraintLayout) popupWindow_view.findViewById(R.id.constraintLayout_menu_add);
        constraintLayout_menu_feedback = (ConstraintLayout) popupWindow_view.findViewById(R.id.constraintLayout_menu_feedback);
        constraintLayout_menu_setting = (ConstraintLayout) popupWindow_view.findViewById(R.id.constraintLayout_menu_setting);
        constraintLayout_menu_exit = (ConstraintLayout) popupWindow_view.findViewById(R.id.constraintLayout_menu_exit);

        //popupwindow的控件事件
        constraintLayout_menu_fan.setOnClickListener(new MyPopupwindowClickListener());
        constraintLayout_menu_blog.setOnClickListener(new MyPopupwindowClickListener());
        constraintLayout_menu_picture.setOnClickListener(new MyPopupwindowClickListener());
        constraintLayout_menu_video.setOnClickListener(new MyPopupwindowClickListener());
        constraintLayout_menu_like.setOnClickListener(new MyPopupwindowClickListener());
        constraintLayout_menu_follow.setOnClickListener(new MyPopupwindowClickListener());
        constraintLayout_menu_question.setOnClickListener(new MyPopupwindowClickListener());
        constraintLayout_menu_add.setOnClickListener(new MyPopupwindowClickListener());
        constraintLayout_menu_feedback.setOnClickListener(new MyPopupwindowClickListener());
        constraintLayout_menu_setting.setOnClickListener(new MyPopupwindowClickListener());
        constraintLayout_menu_exit.setOnClickListener(new MyPopupwindowClickListener());

        //设置字体
        Typeface typeface = ResourcesCompat.getFont(this, R.font.huamao);
        textView_main_app_name.setTypeface(typeface);


        //初始化用户信息
        init();


        //设置初始帧
        Bundle bundle = new Bundle();
        bundle.putSerializable("user", my_info);
        homeFragment.setArguments(bundle);
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.fragmentContainer_outer, homeFragment);
        fragmentTransaction.commit();

        imageView_main_home.setOnClickListener(new MyImageViewClickListener());
        imageView_main_add.setOnClickListener(new MyImageViewClickListener());
        imageView_main_person.setOnClickListener(new MyImageViewClickListener());
        imageView_main_search.setOnClickListener(new MyImageViewClickListener());
        imageView_main_menuBar.setOnClickListener(new MyImageViewClickListener());





    }

    void get_blogs(){
        //网络请求
        try {
            OkHttpClient build = new OkHttpClient.Builder()
                    .connectTimeout(2, TimeUnit.SECONDS)
                    .readTimeout(2, TimeUnit.SECONDS)
                    .writeTimeout(2, TimeUnit.SECONDS)
                    .build();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://129.204.116.253:8080")

                    .addConverterFactory(GsonConverterFactory.create())

                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//新的配置

                    // build 即为okhttp声明的变量，下文会讲
                    .client(build)

                    .build();

            final only_username data_ = new only_username(my_info.getUsername());
            MainActivity.UserBlogService service = retrofit.create(MainActivity.UserBlogService.class);
            service.getFollowBlog(data_)
                    .subscribeOn(Schedulers.io())//请求在新的线程中执行
                    .observeOn(AndroidSchedulers.mainThread())         //请求完成后在主线程中执行
                    .subscribe(new DisposableObserver<User_Info_Activity.User_All_Blogs>() {
                        @Override
                        public void onNext(User_Info_Activity.User_All_Blogs data) {

                            Blog_Data.followBlogs = data.getBlogs();
                        }

                        @Override
                        public void onError(Throwable e) {
                            Toast.makeText(MainActivity.this, "查询博客失败："+ e.toString(), Toast.LENGTH_SHORT).show();
                            Log.i("test", "onError: "+e.toString());
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
            service.getNewBlog(data_)
                    .subscribeOn(Schedulers.io())//请求在新的线程中执行
                    .observeOn(AndroidSchedulers.mainThread())         //请求完成后在主线程中执行
                    .subscribe(new DisposableObserver<User_Info_Activity.User_All_Blogs>() {
                        @Override
                        public void onNext(User_Info_Activity.User_All_Blogs data) {

                            Blog_Data.newBlogs = data.getBlogs();
                        }

                        @Override
                        public void onError(Throwable e) {
                            Toast.makeText(MainActivity.this, "查询博客失败："+ e.toString(), Toast.LENGTH_SHORT).show();
                            Log.i("test", "onError: "+e.toString());
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }catch (Exception o){
            Toast.makeText(MainActivity.this, "抛出异常："+ o.toString(), Toast.LENGTH_SHORT).show();
            Log.i("test", "onError: "+o.toString());
        }
    }

    public interface UserBlogService{
        @POST("/blog/getFollowBlog")
        Observable<User_Info_Activity.User_All_Blogs> getFollowBlog(@Body only_username only_username_);

        @POST("/blog/getNewBlog")
        Observable<User_Info_Activity.User_All_Blogs> getNewBlog(@Body only_username only_username_);
    }


    void init(){
        Blog_Data.followBlogs = new ArrayList<>();
        Blog_Data.likeBlogs = new ArrayList<>();
        Blog_Data.newBlogs = new ArrayList<>();

        Intent intent = getIntent();
        if(intent.getBooleanExtra("register", false)){
            Toast.makeText(MainActivity.this, "欢迎加入猫客", Toast.LENGTH_SHORT).show();
        }
        else {
            Toast.makeText(MainActivity.this, "欢迎回到猫客", Toast.LENGTH_SHORT).show();
        }

        //获得用户信息，用户名，昵称，个人介绍，头像base64
        my_info = (User_basic_info) intent.getSerializableExtra("user");

        get_blogs();


    }



    private class MyPopupwindowClickListener implements ConstraintLayout.OnClickListener{
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.constraintLayout_menu_fan: {
                    /*
                    Intent intent = new Intent(MainActivity.this, MenuFanActivity.class);
                    startActivity(intent);
                    */
                    Intent intent = new Intent(MainActivity.this, UnfinishedActivity.class);
                    startActivity(intent);
                    break;
                }
                case R.id.constraintLayout_menu_blog: {
                    /*
                    Intent intent = new Intent(MainActivity.this, MenuBlogActivity.class);
                    startActivity(intent);
                    */
                    Intent intent = new Intent(MainActivity.this, UnfinishedActivity.class);
                    startActivity(intent);
                    break;
                }
                case R.id.constraintLayout_menu_picture: {
                    Intent intent = new Intent(MainActivity.this, UnfinishedActivity.class);
                    startActivity(intent);

                    break;
                }
                case R.id.constraintLayout_menu_video: {
                    Intent intent = new Intent(MainActivity.this, UnfinishedActivity.class);
                    startActivity(intent);
                    break;
                }
                case R.id.constraintLayout_menu_like: {
                    Intent intent = new Intent(MainActivity.this, UnfinishedActivity.class);
                    startActivity(intent);
                    break;
                }
                case R.id.constraintLayout_menu_follow: {
                    /*
                    Intent intent = new Intent(MainActivity.this, MenuFollowActivity.class);
                    startActivity(intent);
                    */
                    Intent intent = new Intent(MainActivity.this, UnfinishedActivity.class);
                    startActivity(intent);
                    break;
                }
                case R.id.constraintLayout_menu_question: {
                    Intent intent = new Intent(MainActivity.this, UnfinishedActivity.class);
                    startActivity(intent);
                    break;
                }
                case R.id.constraintLayout_menu_add: {
                    /*
                    Intent intent = new Intent(MainActivity.this, WriteBlogActivity.class);
                    startActivity(intent);
                    */
                    Intent intent = new Intent(MainActivity.this, UnfinishedActivity.class);
                    startActivity(intent);
                    break;
                }
                case R.id.constraintLayout_menu_feedback: {
                    Intent intent = new Intent(MainActivity.this, UnfinishedActivity.class);
                    startActivity(intent);
                    break;
                }

                //跳转到更改个人信息
                case R.id.constraintLayout_menu_setting: {

                    Intent intent = new Intent(MainActivity.this, ChangeInfoActivity.class);
                    intent.putExtra("user", my_info);
                    startActivityForResult(intent,1);
                    break;
                }
                case R.id.constraintLayout_menu_exit: {
                    Intent intent = new Intent(MainActivity.this, UnfinishedActivity.class);
                    startActivity(intent);
                    break;
                }
            }
        }
    }


    //修改个人信息返回的数据，判断是否修改过，如果修改过，需要更新个人信息。
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Boolean haschange = data.getBooleanExtra("has_change", false);
        //修改过了，需要更新一下这边的界面，包括左边窗口和个人页面
        if(haschange){
            Toast.makeText(MainActivity.this,"修改成功",Toast.LENGTH_SHORT).show();
            my_info = (User_basic_info) data.getSerializableExtra("user");
            textView_menu_summary.setText(my_info.getDescription());
            Bitmap bm = null;
            byte[] bytes = Base64.decode(my_info.getIcon(), Base64.DEFAULT);
            bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            circleImageView_menu_image.setImageBitmap(bm);
        }
        //未修改，不理
        else {
            Toast.makeText(MainActivity.this,"取消修改",Toast.LENGTH_SHORT).show();
        }
    }



    private class MyImageViewClickListener implements ImageView.OnClickListener {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.imageView_main_home: {
                    //bundle给碎片传输信息，用户信息

                    Bundle bundle = new Bundle();
                    bundle.putSerializable("user", my_info);
                    homeFragment.setArguments(bundle);

                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.fragmentContainer_outer, homeFragment);
                    imageView_main_home.setImageResource(R.mipmap.ic_launcher_home_blue);
                    imageView_main_person.setImageResource(R.mipmap.ic_launcher_person_gray);
                    fragmentTransaction.commit();
                    break;
                }
                case R.id.imageView_main_add: {
                    Intent intent = new Intent(MainActivity.this, WriteBlogActivity.class);
                    intent.putExtra("user", my_info.getUsername());
                    startActivity(intent);
                    break;
                }
                case R.id.imageView_main_person: {//右边个人主页

                    //bundle给碎片传输信息，用户信息
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("user", my_info);
                    personFragment.setArguments(bundle);

                    //
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.fragmentContainer_outer, personFragment);
                    imageView_main_home.setImageResource(R.mipmap.ic_launcher_home_gray);
                    imageView_main_person.setImageResource(R.mipmap.ic_launcher_person_blue);
                    fragmentTransaction.commit();
                    break;
                }
                case R.id.imageView_main_search: {
                    Intent intent = new Intent(MainActivity.this, SearchActivity.class);
                    startActivity(intent);
                    break;
                }
                case R.id.imageView_main_menuBar: {
                    popupWindow = new PopupWindow(popupWindow_view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
                    popupWindow.setFocusable(true);
                    popupWindow.setBackgroundDrawable(new ColorDrawable());

                    popupWindow.setOutsideTouchable(true);
                    //给左边弹出框初始化
                    textView_menu_username.setText(my_info.getUsername());
                    textView_menu_summary.setText(my_info.getDescription());
                    Bitmap bm = null;
                    byte[] bytes = Base64.decode(my_info.getIcon(), Base64.DEFAULT);
                    bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    circleImageView_menu_image.setImageBitmap(bm);

                    popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            constraintLayout_main_container.setAlpha(1.0f);
                        }
                    });
                    constraintLayout_main_container.setAlpha(0.5f);
                    popupWindow.showAtLocation(getLayoutInflater().inflate(R.layout.activity_main, null), Gravity.LEFT, 0, 0);
                    break;
                }
            }

        }
    }


}
